package blog.model;

import blog.beans.User;
import blog.utils.HibernateUtil;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
 *
 * @author Andreas
 */
public class UserHelper {
    Session session = null;
    
    public UserHelper() {
        this.session = HibernateUtil.getSessionFactory().getCurrentSession();
    }
    
    public User getUserById(Integer user_id){
        User user = null;
        try {
            Transaction tx = session.beginTransaction();
            Query q = session.createQuery("from User as user where user.UId=" + user_id);
            user = (User) q.uniqueResult();
        } catch(Exception e) {
            e.printStackTrace();
        }
        return user;
    }
    
    public User getUserByUsername(String username){
        User user = null;
        try {
            Transaction tx = session.beginTransaction();
            Query q = session.createQuery("from User where username='" + username + "'");
            user = (User) q.uniqueResult();
        } catch(Exception e) {
            e.printStackTrace();
        }
        
        return user;
    }
    
    public List<User> getUsers() {
        List<User> user = null;
        try {
            Transaction tx = session.beginTransaction();
            Query q = session.createQuery("from User");
            user = (List<User>) q.list();
        } catch(Exception e) {
            e.printStackTrace();
        }
        
        return user;
    }
    
    public boolean isUser(String username) { 
        Query q = null;
        User user = null;
        
        try {
            Transaction tx = session.beginTransaction();
            q = session.createQuery("from User where username='" + username + "'");
            user = (User) q.uniqueResult();
        } catch(Exception e) {
            e.printStackTrace();
        }
        
        if(user != null){
            return true;
        } else {
            return false;
        }
    }
    
    public boolean isUser(String username, String password) { 
        Query q = null;
        User user = null;
        try {
            Transaction tx = session.beginTransaction();
            q = session.createQuery("from User where username='" + username + "' AND password='" + password + "'");
            user = (User) q.uniqueResult();
        } catch(Exception e) {
            e.printStackTrace();
        }
        
        if(user != null){
            return true;
        } else {
            return false;
        }
    }
    
    public boolean setUser(User user) {
        try {
            Transaction tx = session.beginTransaction();
            session.save(user);
            tx.commit();
            return true;
        } catch(Exception e) {
            return false;
        }
    }
}